package spu

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"insighttracking/apps/customer/auth"
	"insighttracking/common/enum"
	"insighttracking/common/utils"
	"insighttracking/query/bo"
	"insighttracking/query/service"
	"net/http"
	"strconv"

	"insighttracking/apps/customer/internal/svc"
	"insighttracking/apps/customer/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetSpuPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetSpuPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetSpuPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetSpuPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetSpuPageApiLogic) GetSpuPageApi(req *types.GetSpuPageReq) (resp *types.SpuPageResp, err error) {
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return nil, err
	}
	spuBo, count, err := service.SpuService.GetSpuPageApi(l.ctx, bo.SpuPageBoReq{
		Name:         req.Name,                      // 商品名称
		Status:       strconv.Itoa(enum.SpuOnShelf), // 上架状态:1是上架,2是下架
		CategoryId:   req.CategoryId,                // 商品分类
		IsWeighed:    req.IsWeighed,                 // 是否称重,0表示是,1表示否
		SpuType:      req.SpuType,                   // 商品类型,0表示基础商品,1表示加工商品
		PageSize:     req.PageSize,                  // 当前条数
		PageNumber:   req.PageNumber,                // 当前页数
		EnterpriseID: accountInfo.EnterpriseId,      // 关联到enterprise表主键id
	})
	if err != nil {
		return &types.SpuPageResp{
			Data: make([]types.SpuModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      0,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	spuModels := k.Map(spuBo, func(item bo.SpuBo, index int) types.SpuModel {
		return types.SpuModel{
			ID:              item.ID,                                 // 主键id
			Name:            item.Name,                               // 商品名称
			CategoryName:    item.CategoryName,                       // 商品名称
			UnitID:          item.UnitID,                             // 商品,关联到unit表主键id
			UnitName:        item.UnitName,                           // 单位名称
			SalesPrice:      item.SalesPrice.StringFixed(2),          // 销售价
			Sort:            item.Sort,                               // 排序
			ProductImageURL: item.ProductImageURL,                    // 商品图
			SupplierID:      item.SupplierID,                         // 供应商id
			SupplierName:    item.SupplierName,                       // 供应商名称
			BrandID:         item.BrandID,                            // 品牌id
			BrandName:       item.BrandName,                          // 品牌名称
			CreatedAt:       utils.TimestampToString(item.CreatedAt), // 创建时间
			UpdatedAt:       utils.TimestampToString(item.UpdatedAt), // 更新时间
			Spec:            item.Spec,                               // 规格
		}
	})
	return &types.SpuPageResp{
		Data: spuModels,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}

func (l *GetSpuPageApiLogic) GetSpuInfo(req *types.SpuInfoReq) (resp *types.SpuInfoResp, err error) {
	resp = &types.SpuInfoResp{}
	spuEntities, err := service.SpuService.GetSpuByIdListApi(l.ctx, req.Ids)
	if err != nil {
		return nil, err
	}
	ids := make([]int64, 0)
	for _, entity := range spuEntities {
		if entity.Status == enum.SpuOffShelf {
			ids = append(ids, entity.ID)
		}
	}
	resp.Ids = ids
	return
}

func (l *GetSpuPageApiLogic) GetSpuCategory() (resp *types.SpuCategoryResp, err error) {
	resp = &types.SpuCategoryResp{}
	list := make([]*types.CategoryList, 0)
	accountInfo, err := auth.GetAccountInfo(l.svcCtx, l.Request)
	if err != nil {
		return
	}

	categories, err := service.SpuService.GetSpuCategoryApi(l.ctx, accountInfo.EnterpriseId)
	if err != nil {
		return nil, err
	}

	for _, v1 := range categories {
		if v1.ParentID != 0 {
			continue
		}
		childrenCategoryList := make([]*types.ChildrenCategoryList, 0)
		for _, v2 := range categories {
			if v2.ParentID == v1.ID {
				childrenCategoryList = append(childrenCategoryList, &types.ChildrenCategoryList{
					ID:   v2.ID,
					Name: v2.Name,
				})
			}
		}
		list = append(list, &types.CategoryList{
			ID:       v1.ID,
			Name:     v1.Name,
			Children: childrenCategoryList,
		})
	}
	resp.List = list
	return
}
